<?php

class IndexAction extends CommonAction{
    
    private $MSTATUS = array('未托管','已托管','已结算','部分托管','部分结算');
    private $ITEMCOUNT = 20;

    //测试
    public function test() {
        $this->display();
    }
    
    public function index() {
        $ltype = 1;
        import('ORG.Util.Verify');
        if (Verify::isEmpty(I('ltype'))==true) {
            $ltype = I('ltype');
        }
        
        import('ORG.Util.Page');// 导入分页类
        $table1 = array('xia_account'=>'ac','xia_emecheck'=>'eme','xia_user'=>'user','xia_user_info'=>'uif');
        $field1 = 'ac.emailverify,eme.id,eme.count,user.id as uid,user.email,user.ctime,uif.utype,uif.nickname,uif.gender';
        $where1 = ' ac.uid=user.id and eme.uid=user.id and user.id=uif.uid';
        $table23 = array('xia_account'=>'ac','xia_user'=>'user','xia_user_info'=>'uif');
        $field23 = 'ac.id,ac.emailverify,user.id as uid,user.email,user.ctime,uif.utype,uif.nickname,uif.gender';
        $where2 = 'ac.passcheck=0 and ac.uid=user.id and user.id=uif.uid';
        $where3 = 'ac.passcheck=1 and ac.uid=user.id and user.id=uif.uid';
        $sw = I('searchword');
        if ($sw) {
            $swsql = " and uif.nickname like '%".$sw."%'";
            $where1 = $where1.$swsql;
            $where2 = $where2.$swsql;
            $where3 = $where3.$swsql;
        }
        $nowPage = I('p',1);
        if ($ltype==1) {//加急
            $order = 'count desc,ctime desc';
            $count = M('emecheck')->table($table1)->field($field1)->where($where1)->order($order)->count();
            $Page = new Page($count, $this->ITEMCOUNT);
            $resEme = M('emecheck')->table($table1)->field($field1)->where($where1)->page($nowPage.','.$Page->listRows)->order($order)->select();
            $this->assign('list', $resEme);
            $pageUrl = $Page->show();
            //$pageUrl = preg_replace('/Prom-/', '', $pageUrl);
            $this->assign('show', $pageUrl);
        }
        else if ($ltype==2) {
            $order = 'ctime desc';
            $count = M('account')->table($table23)->field($field23)->where($where2)->order($order)->count();
            $Page = new Page($count, $this->ITEMCOUNT);
            $resAc = M('account')->table($table23)->field($field23)->where($where2)->page($nowPage.','.$Page->listRows)->order($order)->select();
            $this->assign('list', $resAc);
            $pageUrl = $Page->show();
            //$pageUrl = preg_replace('/Prom-/', '', $pageUrl);
            $this->assign('show', $pageUrl);
        }
        else if ($ltype==3) {
            $order = 'ctime desc';
            $count = M('account')->table($table23)->field($field23)->where($where3)->order($order)->count();
            $Page = new Page($count, $this->ITEMCOUNT);
            $resAc = M('account')->table($table23)->field($field23)->where($where3)->page($nowPage.','.$Page->listRows)->order($order)->select();
            $this->assign('list', $resAc);
            $pageUrl = $Page->show();
            //$pageUrl = preg_replace('/Prom-/', '', $pageUrl);
            $this->assign('show', $pageUrl);
        }
        
        $this->assign('ltype', $ltype);
        $this->assign('menu', 1);
        $this->display();
    }
    
    //通过审核
    public function acceptCheck_ajax() {
        import('ORG.Util.Verify');
        if (Verify::isEmpty(I('uid'))==false) {
            $this->ajaxf('参数错误!');
        }
        $now = time();
        $uid = I('uid');
        $resAc = M('account')->where('uid='.$uid)->setField('passcheck', 1);
        if ($resAc) {
            $resEme = M('emecheck')->where('uid='.$uid)->delete();
            //发送通知
            //情报
            $content = '<td>喜大普奔！您注册的般若虾账号已<b>通过审核</b>，还等什么，发项目、找人才统统搞起来！</td>';
            $msg = array(
                'uid' => $uid,
                'content' => logPost($content, "", $now),
                'ctime' => $now,
            );
            M('office_log')->add($msg);
            //邮件
            $resUser = M('user')->where('id='.$uid)->find();
            $resUif = M('user_info')->where('uid='.$uid)->find();
            $to = $resUser['email'];
            $name = $resUif['nickname'];
            $subject = "通过审核-般若虾";
            $body = composeMail($name, $content);
            $body = mailPostfix($body);
            mailqueue_push($to, $name, $subject, $body);
            
            $this->ajaxs();
        }
        $this->ajaxf('审核失败!');
    }
    
    //撤销审核
    public function cancelCheck_ajax() {
        import('ORG.Util.Verify');
        if (Verify::isEmpty(I('uid'))==false) {
            $this->ajaxf('参数错误!');
        }
        
        $uid = I('uid');
        $resAc = M('account')->where('uid='.$uid)->setField('passcheck', 0);
        if ($resAc) {
            $this->ajaxs();
        }
        $this->ajaxf('撤销失败!');
    }
    
    //向用户发送消息
    public function sendmsg_ajax() {
        import('ORG.Util.Verify');
        if (Verify::isEmpty(I('receiver'))==false) {
            $this->ajaxf('参数错误!');
        }
        
        $receiver = I('receiver');
        $text = I('text');
        $now = time();
        $data = array(
            'uid' => $receiver,
            'content' => logPost("<td><b>系统消息：</b>".$text.'</td>', "", $now),
            'ctime' => $now,
        );
        $ret = M('office_log')->add($data);
        if ($ret) {
            $this->ajaxs(1, '已发送');
        }
        $this->ajaxf('发送失败');
    }
    
    //资金托管
    public function prjmoney() {
        $ltype = I('ltype', 1);
        $moneyin = $ltype-1;
        $keyword = I('searchword','');
        $field = 'job.id,job.name as jname,job.salary,job.ctime as jctime,prj.id as pid,prj.name as pname,team.id as tid,team.name as tname,uif.uid,uif.nickname as founder';
        $table = array('xia_job'=>'job','xia_project'=>'prj','xia_team'=>'team','xia_user_info'=>'uif');
        import('ORG.Util.Page');
        $nowPage = I('p',1);
        if ($keyword=='') {
            $where = "job.moneyin=".$moneyin." and job.state>0 and job.pid=prj.id and prj.tid=team.id and team.uid=uif.uid";
        }
        else {//搜索
            $where = "job.moneyin=".$moneyin." and job.state>0 and job.pid=prj.id and prj.tid=team.id and team.uid=uif.uid and job.name like '%".$keyword."%'";
        }
        $count = M('job')->table($table)->field($field)->where($where)->count();
        $Page = new Page($count, $this->ITEMCOUNT);
        $list = M('job')->table($table)->field($field)->where($where)->order('jctime desc')->page($nowPage.','.$Page->listRows)->select();
        $this->assign('list', $list);
        $pageUrl = $Page->show();
        //$pageUrl = preg_replace('/Prom-/','',$pageUrl);
        $this->assign('show', $pageUrl);
        $this->assign('ltype', $ltype);
        $this->assign('kw', $keyword);
        $this->assign('menu', 2);
        $this->display();
    }
    
    //设置托管状态
    public function setDelegate() {
        import('ORG.Util.Verify');
        if (Verify::isEmpty(I('status'))==false) {
            $this->ajaxf('状态参数不能为空！');
        }
        $uid = I('uid');
        $jobid = I('id');
        if ($jobid<=0) {
            $this->ajaxf('职位id参数不能为空！');
        }
        $moneyin = I('status');
        if ($moneyin==-1) {
            $moneyin = 0;//撤销托管
        }
        $ret = M('job')->where('id='.$jobid.' and state>0')->setField('moneyin', $moneyin);
        if ($ret) {
            //同步雇员收入统计
            if ($moneyin==2) {
                $resJu = M('job_user')->where('jobid='.$jobid)->find();
                if ($resJu) {
                    M('jobhistory')->where("uid=".$resJu['uid']." and jobid=".$jobid)->save(array('quitype'=>0));
                }
            }
            
            //通知企业
            //情报
            $resJob = M('job')->where('id='.$jobid)->find();
            $resPrj = M('project')->where('id='.$resJob['pid'].' and state>0')->find();
            if ($moneyin==1 || $moneyin==4) {
                $content = "喜大普奔！您用于支付给职位<b>".$resJob['name']."</b>的薪酬<span style='color:#f00;padding:0px 3px;'>￥".$resJob['salary']."</span>般若虾<b>已托管</b>，好人才分分钟到你碗里来！";
            }
            else if($moneyin==2){
                $content = "您的职位<b>".$resJob['name']."</b>已经与雇员结算完毕";
            }
            $now = time();
            $msg = array(
                'uid' => $uid,
                'content' => logPost('<td>'.$content.'</td>', '', $now),
                'ctime' => $now,
            );
            M('office_log')->add($msg);
            //邮件
            $resUser = M('user')->where('id='.$uid)->find();
            $resUif = M('user_info')->where('uid='.$uid)->find();
            $to = $resUser['email'];
            $name = $resUif['nickname'];
            $subject = "职位资金已托管-般若虾";
            $body = composeMail($name, $content);
            $body = mailPostfix($body);
            mailqueue_push($to, $name, $subject, $body);
            
            $this->ajaxs(1, '设置成功！');
        }
        else {
            $this->ajaxs(0, '设置失败！');
        }
    }
    
    //薪酬发放
    public function paysalary() {
        $ltype = I('ltype', 1);
        $keyword = I('searchword','');
        $field = <<<EOF
xia_job.salary,xia_job.name as jn,
xia_project.name as pn,
xia_team.name as tn,xia_team.uid as tl,
xia_jobhistory.quitime,xia_jobhistory.income
EOF;
        $joinJob = "LEFT JOIN xia_job ON xia_jobhistory.jobid = xia_job.id";
        $joinPrj = "LEFT JOIN xia_project ON xia_project.id = xia_job.pid";
        $joinTeam = "LEFT JOIN xia_team ON xia_team.id = xia_project.tid";
        
        import('ORG.Util.Page');
        $nowPage = I('p',1);
        require_once APP_PATH.'/Group/Bridge/Action/BaseAction.class.php';
        if ($ltype==1) {
            $joinJu = "INNER JOIN xia_job_user ON (xia_job_user.uid = xia_jobhistory.uid and xia_jobhistory.quitype=".BaseAction::JOBHIS_QUITYPE_UNQUIT.")";
            $where = 'xia_job_user.pay='.$ltype;
            $field = "xia_job_user.id,xia_job_user.jobid,xia_job_user.uid,xia_job_user.uname,xia_job_user.pay,xia_job_user.pid,".$field;
            if ($keyword!='') {
                $where .= " and j.name like '%".$keyword."%'";
            }
            $count = M('jobhistory')->join($joinJu)->join($joinJob)->join($joinPrj)->join($joinTeam)->field($field)->where($where)->count();
            $Page = new Page($count, $this->ITEMCOUNT);
            $list = M('jobhistory')->join($joinJu)->join($joinJob)->join($joinPrj)->join($joinTeam)->field($field)->where($where)->page($nowPage.','.$Page->listRows)->select();
        }
        else {
            $where = "(xia_jobhistory.quitype IN (".BaseAction::JOBHIS_QUITYPE_SETTLE.",".BaseAction::JOBHIS_QUITYPE_UNQUIT.")) and xia_jobhistory.income>0";
            $field = "xia_user_info.nickname as uname,".$field;
            if ($keyword!='') {
                $where .= " and j.name like '%".$keyword."%'";
            }
            $joinUif = "LEFT JOIN xia_user_info ON xia_user_info.uid=xia_jobhistory.uid";
            $count = M('jobhistory')->join($joinJob)->join($joinPrj)->join($joinTeam)->join($joinUif)->field($field)->where($where)->count();
            $Page = new Page($count, $this->ITEMCOUNT);
            $list = M('jobhistory')->join($joinJob)->join($joinPrj)->join($joinTeam)->join($joinUif)->field($field)->where($where)->page($nowPage.','.$Page->listRows)->select();
        }
        
        $this->assign('list', $list);
        $pageUrl = $Page->show();
        //$pageUrl = preg_replace('/Prom-/','',$pageUrl);
        $this->assign('show', $pageUrl);
        
        $this->assign('ltype',$ltype);
        $this->assign('kw', $keyword);
        $this->assign('menu',3);
        $this->display();
    }
    
    //发送邮件
    public function mail() {
        $nickname = I('nickname');
        $email = I('email');
        $this->assign('nickname', $nickname);
        $this->assign('email', $email);
        
        $subject = I('subject');
        $content = I('content');
        if (!subject || !$content) {
            $this->display();
            exit;
        }
        
        $rlt = 0;
        if (mailqueue_push($email, $nickname, $subject, mailTeampost($content))) {
            $rlt = 1;
        }
        $this->assign('rlt', $rlt);
        $this->display();
    }
    
    //用户信息浏览
    public function userinfo() {
        $uid = I('uid');
        if (!$uid) {
            $this->display();
            exit;
        }
        
        $i = M('user_info')->table(array('xia_user_info'=>'uif','xia_user'=>'u'))->field('uif.*,u.email')->where("u.id='".$uid."' and u.id=uif.uid")->find();
        $this->assign('i', $i);
        $this->display();
    }
    
    //首页推荐位
    public function mpindex() {
        //职位
        $table = array('xia_mpindex'=>'mpi');
        $join1 = 'xia_job as job ON mpi.oid=job.id';
        $join2 = 'xia_project as prj ON job.pid=prj.id';
        $join3 = 'xia_team as team ON prj.tid=team.id';
        $field = "mpi.*,job.id as jid,job.name as jname,team.name as tname";
        $where = "mpi.stype=1";
        $order = "mpi.sortid";
        $jobs = M('job')->table($table)->field($field)->join($join1)->join($join2)->join($join3)->where($where)->order($order)->select();
        if ($jobs) {
            $this->assign('jobs', $jobs);
        }
        
        //人才
        $tableR = array('xia_mpindex'=>'mpi');
        $joinR1 = 'xia_user as user ON user.id=mpi.oid';
        $joinR2 = 'xia_user_info as uif ON uif.uid=mpi.oid';
        $fieldR = "mpi.*,user.email,uif.uid,uif.nickname,uif.teamname";
        $where = "mpi.stype=2";
        $talents = M()->table($tableR)->field($fieldR)->join($joinR1)->join($joinR2)->where($where)->order($order)->select();
        if ($talents) {
            $this->assign('talents', $talents);
        }
        
        $this->assign('menu',4);
        $this->display();
    }
    
    //设置推荐位
    public function recom() {
        $oid = I('oid');
        if (!$oid) {
            $this->assign('errmsg', '用户/职位ID错误!');
            $this->display();
            exit;
        }
        $stype = I('stype');
        
        $pos = I('pos');
        $rlt = false;
        if ($pos) {
            $tabMPI = M('mpindex');
            $res = $tabMPI->where("sortid=".$pos." and stype=".$stype)->find();
            if ($res) {
                $rlt = $tabMPI->where("sortid=".$pos." and stype=".$stype)->save(array('oid'=>$oid));
            }
            else{
                $rlt = $tabMPI->add(array('sortid'=>$pos,'stype'=>$stype,'oid'=>$oid));
            }
            if ($rlt) {
                $this->assign('errmsg', '推荐成功！');
            }
            else {
                $this->assign('errmsg', '推荐失败！');
            }
        }
        if ($stype==2) {
            $user = M('user_info')->where("uid=".$oid)->find();
            $obj = "用户[".$user['nickname']."]";
        }
        else if($stype==1) {
            $job = M('job')->where('id='.$oid)->find();
            $obj ="职位[".$job['name']."]";
        }
        $this->assign('obj',$obj);
        
        $poses = array(1,2,3,4,5,6);
        $this->assign('poses', $poses);
        
        $this->assign('oid', $oid);
        $this->assign('stype', $stype);
        $this->display();
    }
    
    //删除推荐位
    public function delrecom_ajax() {
        $stype = I('stype');
        $pos = I('pos');
        if (empty($stype) || empty($pos)) {
            ajaxf('参数错误！');
        }
        $rlt = M('mpindex')->where("sortid=".$pos." and stype=".$stype)->delete();
        if ($rlt) {
            ajaxs();
        }
        else {
            ajaxf();
        }
    }
    
    //友链管理
    public function fl() {
        $newtitle = I('newtitle');
        $newurl = I('newurl');
        if ($newtitle && $newurl) {
            $this->assign('newtitle', $newtitle);
            $this->assign('newurl', $newurl);
            $resLink = M('friendlink')->where("url='".$newurl."'")->select();
            if ($resLink) {
                $this->assign('notice', '已存在相同url的友链！');
            }
            else {
                $resLink = M('friendlink')->add(array('title'=>$newtitle,'url'=>$newurl));
            }
        }
        
        $resLink = M('friendlink')->select();
        if ($resLink) {
            $this->assign('links', $resLink);
        }
        
        $this->assign('menu', 5);
        $this->display();
    }
    
    //操作友链
    public function togglelink_ajax() {
        $lid = I('link');
        $ot = I('ot');
        $tabLink = M('friendlink');
        if (!$lid || !$ot) {
            ajaxf("参数错误！");
        }
        $ret = false;
        if ($ot==1) {
            $resLink = $tabLink->where('id='.$lid)->find();
            $data = array();
            if ($resLink['status']==0) {
                $data['status'] = 1;
            }
            else {
                $data['status'] = 0;
            }
            $ret = $tabLink->where('id='.$lid)->save($data);
        }
        else if ($ot==2) {
            $ret = $tabLink->where("id=".$lid)->delete();
        }
        if ($ret) {
            ajaxs();
        }
        else {
            ajaxf();
        }
    }
    
    //发放薪酬
    public function setpay() {//TODO LIST:测试设置任意额度线薪酬
        $juid = I('ju');
        $income = I('cost');
        $resJob = array('name'=>'');
        $resJu = M('job_user')->where('id='.$juid)->find();
        $resJob = M('job')->where("id=".$resJu['jobid'])->find();
        if ($income && $income>0) {
            require_once APP_PATH.'/Group/Bridge/Action/BaseAction.class.php';
            $sql = "UPDATE `xia_job` SET `moneyin`=".BaseAction::JOB_SALARYSTATUS_SETTLE." WHERE id=".$resJu['jobid'];
            $ret = M('job')->execute($sql);
            $sql = "UPDATE `xia_job_user` SET `pay`=".BaseAction::JOB_PAYED." WHERE ( id=".$juid." )";
            $ret = M('job_user')->execute($sql);
            if ($ret) {
                //更新收入统计
                $tabJH = M('jobhistory');
                $sql = "UPDATE xia_jobhistory SET income=".$income." where jobid=".$resJu['jobid']." and quitype=".BaseAction::JOBHIS_QUITYPE_UNQUIT;
                $resJH = $tabJH->execute($sql);
                if(!$resJH){
                    Log::write('[setpay]update jobhistory failed! LastSql:'.$tabJH->getLastSql().',error:'.$tabJH->getError(), Log::ERR);
                }
                //通知
                $now = time();
                $textTalent = "<td>般若虾客服已将您任职<b>[".$resJob['name']."]</b>的薪酬<span style='font-family:Arial;font-weight:bold;'>&yen;".$income."</span>汇款至您的账户，请查收！祝您工作愉快！</td>";
                $textTalent = logPost($textTalent, U("/User/income"), $now);
                $textEmploy = "<td>般若虾客服已将职位<b>[".$resJob['name']."]</b>的薪酬<span style='font-family:Arial;font-weight:bold;'>&yen;".$income."</span>支付给人才<b>[".$resJu['uname']."]</b>，祝您工作愉快！</td>";
                $textEmploy = logPost($textEmploy, '', $now);
                //雇主uid
                $resPrj = M('project')->where("id=".$resJob['pid'])->find();
                $resTeam = M('team')->where("id=".$resPrj['tid'])->find();
                //发送通知
                sendNotice($resJu['uid'], $textTalent);
                sendNotice($resTeam['uid'], $textEmploy);
                $this->assign("errmsg", "设置发放成功！");
            }
            else {
                $this->assign("errmsg", '设置发放失败！');
            }
        }
        else {
            $income = $resJob['salary'];
        }
        $this->assign("ju",$juid);
        $this->assign("jname",$resJob['name']);
        $this->assign("recvername", $resJu['uname']);
        $this->assign("income", $income);
        $this->assign('menu',3);
        $this->display();
    }
    
    //统计
    public function stat() {
        $today0 = date('Y-m-d 00:00:00');
        $begin = I('begin', strtotime($today0));
        $nowstr = date('Y-m-d H:i:s');
        $end = I('end');
        if (strlen($begin)<=0) {
            $begin = $today0;
        }
        if (strlen($end)<=0) {
            $end = strtotime($nowstr);
        }
        $utbegin = strtotime($begin);
        $utend = strtotime($end);
        
//        echo $utbegin.",".$utend;
//        exit;
        
        $this->assign('begin',$begin);
        $this->assign('end',$end);
        
        $nowPage = I('p',1);
        
        //$sql = "SELECT ac.id,ac.emailverify,user.id as uid,user.email,user.ctime,uif.utype,uif.nickname,uif.gender FROM `xia_account` `ac`,`xia_user` `user`,`xia_user_info` `uif` WHERE ( ac.passcheck=0 and ac.uid=user.id and user.id=uif.uid ) ORDER BY ctime desc LIMIT 0,20";
        $table = array('xia_account'=>'ac', 'xia_user'=>'user', 'xia_user_info'=>'uif');
        $field = "ac.id,ac.emailverify,ac.passcheck,user.id,uif.uid,user.email,user.ctime,uif.utype,uif.nickname,uif.gender";
        $where = "ac.uid=user.id and user.id=uif.uid and user.ctime>=".$begin." and user.ctime<=".$end;
        $order = "user.ctime DESC";
        $tabAc = M('account');
        $count = $tabAc->table($table)->field($field)->where($where)->count(); //总数
        $tcount = M('user')->table(array('xia_user'=>'u', 'xia_user_info'=>'uif'))->where("uif.utype=1 and u.ctime>=".$begin." and u.ctime<=".$end." and u.id=uif.uid")->count(); //个人用户数
        $ecount = M('user')->table(array('xia_user'=>'u', 'xia_user_info'=>'uif'))->where("uif.utype=2 and u.ctime>=".$begin." and u.ctime<=".$end." and u.id=uif.uid")->count(); //企业用户数
        $this->assign("total", $count);
        $this->assign('tcount', $tcount);
        $this->assign('ecount', $ecount);
        
        import('ORG.Util.Page');// 导入分页类
        $Page = new Page($count, $this->ITEMCOUNT);
        $resAc = $tabAc->table($table)->field($field)->where($where)->page($nowPage.','.$Page->listRows)->order($order)->select();
        
        $this->assign('list', $resAc);
        $pageUrl = $Page->show();
        //$pageUrl = preg_replace('/Prom-/', '', $pageUrl);
        $this->assign('page', $pageUrl);
        $this->display();
    }
}
